/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.model;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author Walter Luetgenau, copied from BalusC, the great and sympathetic developer of numerous, very helpful web 
 */
public class AppletUtil {
    /**
     * Create a query string based on the given parameter map and the given charset encoding.
     * @param parameterMap The parameter map to be processed as query parameters.
     * @param charset The encoding to be applied.
     * @return The parameter map as query string.
     * @throws UnsupportedEncodingException If the given charset is not supported.
     */
    public static String createQuery(Map<String, String[]> parameterMap, String charset)
        throws UnsupportedEncodingException
    {
        if ( parameterMap.size() == 0)
            return "";
        
        StringBuilder query = new StringBuilder("?");

        for (Iterator<String> names = parameterMap.keySet().iterator(); names.hasNext();) {
            String name = names.next();
            String[] values = parameterMap.get(name);

            for (int i = 0; i < values.length;) {
                query.append(URLEncoder.encode(name, charset));
                query.append("=");
                query.append(URLEncoder.encode(values[i], charset));

                if (++i < values.length) {
                    query.append("&");
                }
            }

            if (names.hasNext()) {
                query.append("&");
            }
        }

        return query.toString();
    }
}
